package nl.leiden.activities;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import nl.leiden.R;
import android.app.Activity;
import android.app.PendingIntent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.telephony.SmsManager;

public class SendActivity extends Activity {
	
	//----------------------------------------------------
	//private GestureLibrary gesturesLibActions;
    
    private StringBuffer sBufferGestureText = new StringBuffer();
    private String sGestureText = new String();
    private String sMessage = new String();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_send);
        
        /*Button previous = (Button) findViewById(R.id.ButtonSendPrevious);
        previous.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ReviewActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });

        Button next = (Button) findViewById(R.id.ButtonSendNext);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ContactsActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });*/
        
		Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		long[] pattern = {0, 200, 200, 200, 200, 200, 200, 200};
		v.vibrate(pattern, -1);
        
        //-- load gesture libraries
        /*gesturesLibActions = GestureLibraries.fromRawResource(this, R.raw.gestures_lib_actions);
        if(!this.gesturesLibActions.load()) {
        	this.finish();
        }*/
        
        //-- get gesture overlay view to add on gesture performed listener
        //GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
        //gestures.addOnGesturePerformedListener(this);
        
        //-- get sMessage from preferences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        sMessage = preferences.getString("sMessage", "");
        
        //-- reset buffer with content from preferences
        this.sBufferGestureText.delete(0, this.sBufferGestureText.length());
        this.sBufferGestureText.append( sMessage );
        this.sGestureText = sBufferGestureText.toString();
       
        //-- set sMessage to TextView on Screen
        TextView tv = (TextView) findViewById(R.id.SendMessageTextView);
        tv.setText(sMessage);
        
        //--delay and then execute runnable
        final Handler handler = new Handler(); 
        Timer t = new Timer(); 
        t.schedule(new TimerTask() { 
                public void run() { 
                        handler.post(new Runnable() { 
                                public void run() { 
                                	runAfterDelay();
                                } 
                        }); 
                } 
        }, 2000); 

    }
    
    //----------------------------------------------------
    public void runAfterDelay() {
    	
    	//--start sending message
		for(int i = 0; i < 100; i++){
			String j = Integer.toString(i);
			SharedPreferences phoneNumbers = getBaseContext().getSharedPreferences("phonenumber_list", MODE_PRIVATE);
			//SharedPreferences contacts = getBaseContext().getSharedPreferences("contact_list", MODE_PRIVATE);
			if (phoneNumbers.contains(j)){
				String Number = phoneNumbers.getString(j, "");
				//String Contact = contacts.getString(j, "");
				sendSMS(Number, sMessage);
			}
			else 
				i = 101;
		}
		
		cleanUp();
		
		Intent myIntent = new Intent(this, ContactsActivity.class);
        this.startActivity(myIntent);
    }
    
    //----------------------------------------------------
    /*public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
    	//--recognize libraries
    	ArrayList<Prediction> predictionsActions = gesturesLibActions.recognize(gesture);

		// We want at least one prediction
		if (predictionsActions.size() > 0) {
			Prediction prediction = predictionsActions.get(0);
			// We want at least some confidence in the result
			if (prediction.score > 1.5) {
				
				//--action name
				String action = predictionsActions.get(0).name;
				
				//--action: confirm
				if ("action_confirm".equals(action)) {
			        //--get the phonenumbers from preferences and send the message to those numbers
					for(int i = 0; i < 100; i++){
						String j = Integer.toString(i);
						SharedPreferences phoneNumbers = getBaseContext().getSharedPreferences("phonenumber_list", MODE_PRIVATE);
						SharedPreferences contacts = getBaseContext().getSharedPreferences("contact_list", MODE_PRIVATE);
						if (phoneNumbers.contains(j)){
							String Number = phoneNumbers.getString(j, "");
							String Contact = contacts.getString(j, "");
							sendSMS(Number, sMessage, Contact);
						}
						else 
							i = 101;
					}
					
					cleanUp();
					
					Intent myIntent = new Intent(this, ContactsActivity.class);
	                this.startActivity(myIntent);
				}
				
				//--action: goback
				else if ("action_goback".equals(action)) {					
					Intent myIntent = new Intent(this, ReviewActivity.class);
	                this.startActivity(myIntent);
				}

			} else {
				Toast.makeText(this, "gesture not recognized", Toast.LENGTH_SHORT).show();
			}
			
		}
	}*/
    
    //--Clears all data from Preference so we can make a new message.
    private void cleanUp(){
    	//First clear the data from contacts and phonenumbers
		for(int i = 0; i < 100; i++){
			String j = Integer.toString(i);
			SharedPreferences phoneNumbers = getBaseContext().getSharedPreferences("phonenumber_list", MODE_PRIVATE);
			SharedPreferences.Editor phoneNumbersEditor = phoneNumbers.edit();
			//SharedPreferences contacts = getBaseContext().getSharedPreferences("contact_list", MODE_PRIVATE);
	        //SharedPreferences.Editor contactsEditor = contacts.edit();
			if (phoneNumbers.contains(j)){
	        	phoneNumbersEditor.clear();
	        	phoneNumbersEditor.commit();
				//contactsEditor.clear();
				//contactsEditor.commit();
			}
			else 
				i = 101;
		}
		
		//Clear the message string from preferences 
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString("sMessage", "");
        editor.commit();    	
    }
    
    //--Send the message to the contact
    private void sendSMS(String phoneNumber, String message){
    	String SENT = "SMS_SENT";
    	String DELIVERED = "SMS_DELIVERED";
    	
    	PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
    	PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
    	
    	//--When the SMS has been send
    	registerReceiver(new BroadcastReceiver(){
    		@Override
    		public void onReceive(Context arg0, Intent arg1){
    			switch (getResultCode()){
    				case Activity.RESULT_OK:
    					Toast.makeText(getBaseContext(), "The message has been sent.", Toast.LENGTH_SHORT).show();
    					break;
    				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
    					Toast.makeText(getBaseContext(), "There was an error. The message has not been sent.", Toast.LENGTH_SHORT).show();
    					break;
    				case SmsManager.RESULT_ERROR_NO_SERVICE:
    					Toast.makeText(getBaseContext(), "You have no service. The message has not been sent", Toast.LENGTH_SHORT).show();
    					break;
    				case SmsManager.RESULT_ERROR_RADIO_OFF:
    					Toast.makeText(getBaseContext(), "The radio is turned off. The message has not been sent", Toast.LENGTH_SHORT).show();
    					break;
    				case SmsManager.RESULT_ERROR_NULL_PDU:
    					Toast.makeText(getBaseContext(), "There was an error (PDU). The message has not been sent", Toast.LENGTH_SHORT).show();
    					break;
    			}
    		}
    		
    	}, new IntentFilter(SENT));
    	
    	//--When the SMS has been delivered
    	registerReceiver(new BroadcastReceiver(){
    		@Override
    		public void onReceive(Context arg0, Intent arg1){
    			switch (getResultCode()){
    				case Activity.RESULT_OK:
    					Toast.makeText(getBaseContext(), "The message has been delivered.", Toast.LENGTH_SHORT).show();
    					break;
    				case Activity.RESULT_CANCELED:
    					Toast.makeText(getBaseContext(), "There was an error. The message has not been delivered.", Toast.LENGTH_SHORT).show();
    					break;
    			}
    		}
    		
    	}, new IntentFilter(DELIVERED));   	
    
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);  
    }
}